# Seymore - Content Management on Rails
# 
# Copyright (c) 2006 - 2007 Thomas Mango
# 
# For license information, please visit:
# http://code.google.com/p/seymore/
# 
# File created by Thomas Mango [tsmango@gmail.com]

class Page < ActiveRecord::Base
  belongs_to    :parent, :class_name => "Page"
  acts_as_list  :scope => :parent_id
  has_many      :children, :class_name => "Page", :foreign_key => "parent_id", :order => "position", :dependent => :destroy
  acts_as_tree  :order => "position"
  
  has_many :revisions, :dependent => :delete_all
  
  validates_presence_of :name, :on => :create, :message => "can't be blank"
  validates_uniqueness_of :name, :on => :save, :message => "must be unique"
  validates_uniqueness_of :slug, :on => :save, :message => "must be unique"
  
  def before_save
    self.slug = Util::Slug.generate(self.name)
  end
  
  def has_published_revision?
    if Page.find_by_sql(["SELECT p.* from pages p LEFT JOIN revisions r ON p.id = r.page_id WHERE p.id = ? AND r.published = true", id]).size > 0
      return true
    else
      return false
    end
  end
  
  def self.reset_child_positions(page)
    position = 1
    for child in page.children
      child.update_attribute('position', position)
      reset_child_positions(child)
      position = position + 1
    end
  end
end
